import React, { useEffect, useLayoutEffect, useState } from 'react';
import { LoadingOutlined, UploadOutlined } from '@ant-design/icons';
import { Upload, UploadFile } from 'antd';
import { IUploadResultItem, uploadImageApi } from '@/services';
import { IEnterpriseItem } from '@/services/enterprise';

interface UploadImageViewProps {
  className?: string;
  maxCnt: number;
  defaultList: UploadFile[];
  uploadTitle: string;
  multiple: boolean;
  onComplete: (data: IUploadResultItem[]) => void;
}
const UploadImageView: React.FC<UploadImageViewProps> = (props) => {
  const [fileList, setFileList] = React.useState<UploadFile[]>([]);
  const [uploadLoading, setUploadLoading] = useState(false);
  const beforeUpload = async (file: File, complete: (data: IUploadResultItem) => void) => {
    setUploadLoading(true);
    const formData = new FormData();
    formData.append('file', file);
    const { code, data } = await uploadImageApi(formData);
    if (code === 0 && data) {
      complete(data);
    }
    setUploadLoading(false);
  };

  useEffect(() => {
    setFileList(props.defaultList);
  });

  const handerComplete = (files: UploadFile[]) => {
    const tempItems: IUploadResultItem[] = [];
    files.forEach((item) => {
      if (item.url) {
        tempItems.push({
          uploaded_file_id: Number(item.uid),
          url: item.url,
        });
      }
    });
    props.onComplete(tempItems);
  };
  const uploadButton = () => (
    <button style={{ border: 0, background: 'none' }} type="button">
      {uploadLoading ? <LoadingOutlined /> : <UploadOutlined />}
      <div style={{ marginTop: 8 }}>{props.uploadTitle}</div>
    </button>
  );

  return (
    <div className={props.className}>
      <Upload
        listType="picture-card"
        accept=".jpg,.bmp,.png,.jpeg"
        maxCount={props.maxCnt}
        multiple={props.multiple}
        beforeUpload={(file) =>
          beforeUpload(file, (data) => {
            const tempFiles: UploadFile[] = fileList;
            const file: UploadFile = {
              url: data.url,
              uid: data.uploaded_file_id.toString(),
            };
            tempFiles.push(file);
            handerComplete(tempFiles);
            setFileList(tempFiles);
          })
        }
        fileList={props.defaultList}
        onRemove={(file) => {
          const files = fileList.filter((item) => item.uid !== file.uid);
          handerComplete(files);
          setFileList(files);
        }}
      >
        {fileList.length >= props.maxCnt ? null : uploadButton()}
      </Upload>
    </div>
  );
};
export default UploadImageView;
